Home > Enterprise >  What is setAttribute arguments in JavaScript?
What is setAttribute arguments in JavaScript?

Time:10-22

can someone please explain to me what is the setAttribute arguments here? I know only that .png is the extension of the image that I will include later in my code.

function setImg(dieImg)
{
  var value = Math.floor( 1   Math.random()*6);
  dieImg.setAttribute( "scr" , "die"   value   
  dieImg.setAttribute( "alt" , "die Image with "   value   "spot(s)");
}

CodePudding user response:

function setImg(dieImg) { var value = Math.floor( 1   Math.random()*6); dieImg.setAttribute( "scr" , "die"   value    dieImg.setAttribute( "alt" , "die Image with "   value   "spot(s)"); } 

First of all, we need to know about tag. It has several attributes for showing and manipulating image.

https://www.w3schools.com/tags/tag_img.asp

src ( you miswritten) attribute is for indicating the source of image so that it should be url of the source.

alt attribute is for alternative string if the given image with url doesn't exist.

For example,

 <img src="https://example.com/image_path.png" alt="Die with....">

setAttribute() function is to add these attribute programmatically.

So I think you miswritten the code

function setImg(dieImg) { var value = Math.floor( 1   Math.random()*6); dieImg.setAttribute( "scr" , "https://example.com/image_path.png" );
dieImg.setAttribute( "alt" , "die Image with "   value   "spot(s)"); } 

Hope it will be helpful

CodePudding user response:

The setAttribute() is a JavaScript method that sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

Syntax: setAttribute(name, value)

For example, you can use the setAttribute() method to change the id attribute on a button, or even to change the content of the style attribute of any element:

const button = document.querySelector("button");

button.setAttribute("id", "anotherButtonID");
button.setAttribute("style", "background-color: blue; color: red");
<button id="myButton">Hello World</button>

You can find more documentation on the setAttribute() method on the MDN WebDocs here.

So, getting back to your question, in this case, with the first parameter, you are changing the src attribute of your image (which specifies the source url). For the second parameter, this code is using string concatenation to pass in the new url source for the image (for example "Hello" " " "world!" will result in "Hello world!".

I hope this helps!

  • Related