When I try the following:
<html>
<body>
<script type="text/javascript">
window.onload = function() {
var test1 = document.getElementsByName("div1");
alert(test1[0]);
var test2 = test1[0].getElementsByName("div2");
alert(test2[0]);
}
</script>
<div name="div1">
<div name="div2">
</div>
</div>
</body>
</html>
It doesn't work the way I intend it to. I made a form and I need to be able to get the form data in a similar manner to what I was testing with this.
getElementsByName should only be called from a document element:
var test2 = document.getElementsByName('div2');
What's more, you really should only use the name attribute for form elements, not divs.
If you want an API that more-easily lets you do searches within a DOM element, consider using jQuery:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(function() {
var div1 = $('#div1');
var div2 = div1.find('#div2');
});
</script>
</head>
<body>
<div id="div1">
<div id="div2"></div>
</div>
</body>
</html>
Of course, since ids must be unique document-wide, there's usually no reason to search within another element for a specific ID. Therefore, you don't really need anything fancy like jQuery for something that simple.
If I recall correctly, only the document (HTMLDocument) has the getElementsByName method. DOM Elements do not have that method and you cannot apply it by using them as the context.
There is no name in div's attributes. Why not use id instead?
Related
Basically I have a bunch of <h2> tags and without going into detail, I can't manually assign them IDs. So I THINK I could use .innerhtml to somehow get the <h2> text and assign that as IDs for them but I'm not sure how to get started.
Is this even possible?
The html would look something like this:
<body>
<h2>Science</h2>
<h2>History</h2>
<h2>Mathematics</h2>
<script>
</script>
</body>
As the comments have said, you should avoid using innerHTML unless you are sure you want the HTML content of the element - Using innerText instead will make sure you only receive the plaintext
You can use querySelectorAll to get all of the h2 elements in an HTMLCollection
You can then simply loop over this and update the property directly by using:
ele.id = ele.innerText;
Or you can make use of setAttribute like this:
ele.setAttribute('id', ele.innerText);
.
You might also want to use .toLowerCase() after the innerHTML, just to have a more standard ID styling
document.querySelectorAll('h2').forEach((ele) => {
ele.id = ele.innerText;
});
console.log(document.getElementById('History').innerText);
<body>
<h2>Science</h2>
<h2>History</h2>
<h2>Mathematics</h2>
<script>
</script>
</body>
You will want to use the DOM to find all the h2 elements and process accordingly:
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h2>Science</h2>
<h2>History</h2>
<h2>Mathematics</h2>
<script>
var h2s = document.querySelectorAll('h2');
h2s.forEach(function(h2Element) {
h2Element.id = h2Element.innerText;
});
</script>
</body>
</html>
I need to get all the content of page including all codes on JavaScript alert. Please check the code.
function getContent() {
var content = document.getElementsByTagName('html').value;
alert(content);
}
<html>
<head>
</head>
<body>
Some more code..........
Get Content
</body>
</html>
I am trying to execute the function from inside the page and trying to get the value. It is giving me undefined error
.getElementsByTagName() returns a NodeList collection of elements. You need to access the first index with [0]. In addition to this, it does not have a .value property. You're looking for .innerHTML instead.
Note that you also shouldn't make use of onclick, and instead should make use of unobtrusive JavaScript by adding an event listener.
This can be seen in the following:
function getContent() {
var content = document.getElementsByTagName('html')[0].innerHTML;
alert(content);
}
document.getElementsByTagName('a')[0].addEventListener('click', getContent);
<html>
<head></head>
<body>
Some more code..........
Get Content
</body>
</html>
Note: this will not work as expected in a Fiddle, but will work as expected on a proper website.
This can be achieved via the innerHTML field of a DOM element. Consider making the following changes to your getContent() function:
function getContent() {
var { innerHTML } = document.querySelector('html');
alert(innerHTML);
}
<html>
<head>
</head>
<body>
Some more code..........
<p> and some more content </p>
Get Content
</body>
</html>
I am working with HTML, CSS, jQuery, and JavaScript, all on one HTML page. Generally, I trying to figure out for the first time how to access information from the HTML body for use in my JavaScript code.
I want to set a variable in JavaScript equal to the string contained in the data attribute of one of my <div> elements.
Can I use document.getElementsByClassName()[] in my JavaScript to actually pull the information out of the HTML document? In examples on W3schools and elsewhere, I only see it used to change the value of some HTML element, not to actually use its input. Is there something more fundamental that I'm missing, here?
____here's my more specific code (where div.onlyOne is the only div of that class, and has the data-need attribute "string i need"):
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need")
Why will this not store "string i need" into myVar?
It works, make sure though, that you run the script after the markup or DOM load, or else the script will not find the element as it has not yet been loaded.
After in markup
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<div class="onlyOne" data-need="hey there"></div>
<script type="text/javascript">
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
</script>
</body>
</html>
DOM load
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
});
</script>
</head>
<body>
<div class="onlyOne" data-need="hey there"></div>
</body>
</html>
May I suggest you use document.querySelector('.onlyOne') instead in the future. With that you can narrow down the result list in a more efficient way.
Src: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
<div class="onlyOne" data-need="some text">...</div>
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
https://jsfiddle.net/howa6w1o/
since you are using jQuery, you can simplify your code to get the contents of the data-attribute: as follows:
$(document).ready(function(){
var myVar = $(".onlyOne").eq(0).data("need");
})
Given i have a sample page that looks like this:
<!DOCTYPE html>
<html>
<body>
<h1 aria-controls="name1">heading</h1>
<p aria-controls="name2">paragraph</p>
<span aria-controls="name1">span</span>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
How would i use jQuery to select the (2) elements with their aria-controls attribute set to name1? (ignoring the fact that the element types are different).
Thank you!
The attribute selector
[aria-controls="name1"]
should work.
Docs: http://api.jquery.com/attribute-equals-selector/
Use something like this -
WORKING DEMO
var elements = $("body").find("[aria-controls='name1']");
Above is for if you want to look for elements within a container eg body in this case, it can be some div also.
--OR--
var elements = $("[aria-controls='name1']");
Above is for if you want to get all the elements with this attribute
<body>
<div id="outer">
<script>var e = document.createElement("div");
e.id = "inner1";
document.body.appendChild(e);</script>
<script>document.write("<div id='inner2'></div>");</script>
The structure I want would be:
html>body>div#outer>div#inner1+div#inner2
the structure I get is:
html>body>(div#outer>div#inner2)+div#inner1
This is terrible beyond my ability to describe, but appears to work for your given situation (I can't tell if you want inner1 and inner2 as children or siblings of outer. this arranges them as siblings).
<body>
<div id="outer">
<script>
var e = document.createElement("div");
e.id = "inner1";
document.body.appendChild(e);
</script>
<script>
var scr = '<script>';
scr += "document.write(\"</div><div id='inner2'>\"); ";
scr += '<' + '/script>';
document.write(scr);
</script>
the closing </script> string is divided to keep the parser from imploding.
how about this?
<script>
// document.write("<div id='inner2'></div>");
var inner2 = document.createElement('div');
inner2.id = 'inner2';
//document.getElementById('outer').appendChild(inner2); //as a child of outer
document.body.appendChild(inner2); // as a sibling of outer
</script>
Look into the jquery documentation. Jquery is a javascript library that you include in your page header. It provides a ton of useful methods for working with the DOM. jQuery is my first choice for writing javascript these days. Straight up js just feels old school to me now. Knowing how to use jQuery effectively (or at least some js library) is a skill every web developer should have. jQuery provides methods like $('css-selector-here').append('what you want to insert'), .prepend(), .insertBefore(), insertAfter(), and .html(), among many others, one of which would probably suit your needs.
Here is a list of all the DOM manipulatuion methods:
http://api.jquery.com/category/manipulation/
Can I clarify your question?
You are getting the following:
<html>
<body>
<div id='outer'>
<div id='inner2'></div>
</div>
<div id='inner1'></div>
</body>
</html>
But what you want is:
<html>
<body>
<div id='outer'>
<div id='inner2'></div>
<div id='inner1'></div>
</div>
</body>
</html>
As long as your div#outer is already defined, you can do the following using jQuery. Quick and easy copy & paste. Please give it a shot!
//If you don't already have jQuery, load it from CDN
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { //Executes after DOM is ready
$("#outer")
.append("<div id='inner1'>INNER DIV 1</div>")
.append("<div id='inner2'>INNER DIV 2</div>");
});
</script>