2

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"

prem p
  • 23
  • 3

5 Answers5

0

You Can Try this

also follow this link 100% of your solution dynamically change label 'for' attribute in with Jquery

$("input, select").each(function(){


var fieldName = $(this).attr('name');



$(this).siblings().attr('for', fieldName);

});
Rakesh kumar Oad
  • 1,332
  • 1
  • 15
  • 24
0

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")
sherlocked982
  • 33
  • 1
  • 1
  • 5
0

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>
Negi Rox
  • 3,828
  • 1
  • 11
  • 18
0

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>
Vishnu Prasanth G
  • 1,133
  • 12
  • 12
0

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

TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29