Reputation: 147
How do I get the variable in the titleText "Some Name" from the JS file to populate or take the title from the hyperlink "sometitle" in the HTML code?
JS
var randomtext={ titleText:"Some Name",}
HTML
<a class="css" title="sometitle" href="#">Your HTML Here</a>
I would like the JS to then change to:
JS
var randomtext={ titleText:"sometitle",}
Titletext name coming from the title in the anchor of the hyperlink
I tried the following and it didn't work
JS
var randomtext={
titleText:document.getElementsByClassName('css')[0]; randomtext.titleText = anchor.getAttribute('title');,
title2: "name1",
title3: "name3",
title4: "name4",
}
Upvotes: 0
Views: 4017
Reputation: 29271
This assumes that you want to get the "title" attribute on the anchor, and use it to set the value of the titleText
property on your randomtext
object:
JS
var randomtext={ titleText:"Some Name"}
// a more specific class name or id would be better suited here
var anchor = document.getElementsByClassName('css')[0];
randomtext.titleText = anchor.getAttribute('title');
Update
I'm not sure why you want to include all the of the logic in your object definition, but your current javascript is invalid. If you absolutely must assign a value to the titleText property when you create your randomText object, the following should work:
var randomtext={
// this immediately invokes a function
// which looks for the first anchor
// and returns it's title attribute
// that attribute is then assigned to the titleText property
// on the object.
titleText:(function () {
var anchor = document.getElementsByClassName('css')[0];
return anchor.getAttribute('title');
})(),
title2: "name1",
title3: "name3",
title4: "name4",
}
Upvotes: 1
Reputation: 2429
First, you need to identify the <a>
element somehow. The easiest way would be to give it an ID.
Then, using document.getElementById
, you can access the hyperlink inside your script. Once that's done, you can access its title with setAttribute
and getAttribute
.
HTML
<a id="myLink" class="css" title="sometitle" href="#">Your HTML Here</a>
JavaScript
var link = document.getElementById("myLink");
// Take the title from the link
var randomText = { titleText: link.getAttribute("title") };
// Change the link's title
link.setAttribute("title", randomText.titleText);
I hope this is what you asked for, because, if I'm honest, I'm not really sure what you wanted to say.
Upvotes: 1