How to add ID attribute to label with its label name. Label doesn't contain any ID(Ex: id="width-label")

Viewed 118

I want to add ID attribute to label using label name. Using jQuery.

<label class="coral-Form-fieldlable">Width</label>
<label class="coral-Form-fieldlabel">Height</label>
<label class="coral-Form-fieldlabel">Quality</label>
<label class="coral-Form-fieldlabel">Color List</label>

In Dom there are multiple class exist with same class name class="coral-Form-fieldable". I want to add ID attribute for only one not all 'label' by using label name = "Width"

5 Answers

You can try this one

function getElementByValue(selector, value) {
  let elements = document.querySelectorAll(selector);
  for (let element of elements) {
    if (element.innerText.indexOf(value) != -1) {
      return element;
    }
  }
  return null;
}

// Call it 
getElementByValue(".coral-Form-fieldable","Width")

It's pretty simple you can use the below code.

$(document).ready(function(){
    $(".coral-Form-fieldable").each(function(i,o){
       var current=$(this);
       current.attr("id",current.text());
       console.log(current.attr("id"));
    })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="coral-Form-fieldable">Width</label>

Add this simple code, you can prefix/suffix the "labelValue" variable while setting the id, because there may be duplicate labels sometimes.

document.querySelectorAll(".coral-Form-fieldable").forEach(function(eachElem){
        var labelValue = eachElem.innerText.trim().replace(/\s/g,"_");
        eachElem.setAttribute("id",labelValue);
});
<h1 class="coral-Form-fieldable">Element H1</h1>
<p class="coral-Form-fieldable">Element P</p>
<div class="coral-Form-fieldable">Element Div</div>

as others mentioned, you should use attr (for more information please check this link).

you can add id attribute to any element by this part of code:

$('element').attr('id', 'value');

for your problem, you can change the element part with .coral-Form-fieldable but please pay attention, classes return an array. so you have to add a for loop

Related