Jajosz Afrykański
Jajosz Afrykański

Reputation: 73

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>

Upvotes: 5

Views: 24938

Answers (3)

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

You can use Document.querySelectorAll():

function myFunction2() {  
  var elements = document.querySelectorAll('.menu-item-has-children');
  
  if (elements.length) {
    elements[0].id = 'menu';
  }
}
#menu {color:red;}
<div class="menu-item menu-item-object-custom menu-item-has-children">
  I am a DIV or LI element
</div>

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

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

Upvotes: 0

Learner
Learner

Reputation: 281

When you get that element by class name, use following way to give id to yur element

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

Upvotes: 0

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24590

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:

Upvotes: 12

Related Questions