Home > Software design >  How to reach a html <span> tag inside a <div> using Java Script?
How to reach a html <span> tag inside a <div> using Java Script?

Time:12-12

I've got a span tag which placed inside a div, like below:

<div onclick="doActiveCheckBox('color1')" id="sss"  >
     <input  type="radio" name="color" id="color1" data-bs-label="colorOption" value="/تاریک" checked="">                                
     <label  for="color1"><span style="border:inherit; border-block-color:purple;"   style="background-image: url(/img/ProductColors/green1.jpg)"></span></label>
</div>

I want to set a border for the span tag as the input tag is clicked and also don't want to use any id in the span. I've tried the bellow ways:

1:

        var d=document.getElementById("sss").getElementsByTagName("span");
        d.style.border = "thick solid #0000FF";

2:

        var d=document.getElementById("sss").getElementsByClassName();
        for (var i = 1; i <= d.length; i  ) {
            d[1].style.border = "thick solid #0000FF";
        }

but none of them worked correctly! So would anybody help?

CodePudding user response:

I would suggest to use querySelector: const d = document.querySelector("#sss span");

And then you can add style: d.style.border = "thick solid #0000FF";

CodePudding user response:

  var d=document.getElementById("sss").getElementsByTagName("span");
                                                 ^//returns an array
d.get.style.border = "thick solid #0000FF";//d[0].style
//┗━━┛ 

There is not a property called get, so access the first element since getElementsByTagName return an array.

CodePudding user response:

To get the span you can do this

var span = document.querySelector("#sss label span");
//do whatever you want with the span

CodePudding user response:

Jquery method if needed

var span = $("#sss label span");
span.css("border", "thick solid #0000FF");

or if you're not using #sss just the inputs (may get multiple results)

var span = $("input.form-check label span");

CodePudding user response:

You could Do These steps to get any HTML ELEMENT and STYLE it using CSS or use it using JS by document.querySelector
1.
enter image description here

2. enter image description here

3. enter image description here

  • Related