Search code examples
javascriptclassadditionelement

How add ID element to the specific class line?


I would like to add an ID to a line that contains a class with the specified name. eg. If the website will block "div" or "li" that contains a class with names such as "name-1 name-2 name-3" This function detects a class called "name-1" and insert element id="menu" that the line looks like this: . Can you help? I tried that:

<div class="menu-item menu-item-object-custom menu-item-has-children">
I am a DIV or LI element
</div>

<button onclick="myFunction2()">Try it</button>

<script>
function myFunction2() {
    var x = document.getElementsByClassName("menu-item-has-children")[0];
        x.document.createElement("id");
}
</script>


Solution

  • You don't need document this what you need:

    function myFunction2() {
        var x = document.getElementsByClassName("menu-item-has-children")[0];
            x.id="menu"
    }
    

    But you should look into jQuery for things like that:

    $('.menu-item-has-children').attr('id','menu')
    

    All you need to do for using jQuery is to add this tag:

    <script src=https://code.jquery.com/jquery-1.11.3.min.js></script> to your HEAD element.


    You can start learn jQuery by learning about selectors, and attr. Using this links: