Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 932
Jajosz Afrykański Avatar asked Dec 23 '22 21:12

Jajosz Afrykański


1 Answers

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:

  • jQuery Selectors
  • jQuery attr function
like image 156
Aminadav Glickshtein Avatar answered Dec 26 '22 10:12

Aminadav Glickshtein