I am trying to reference elements (to get pieces of text) in a news website and display them in a simple way.
I watched a YouTube tutorial about referencing elements and it referenced paragraphs using 'getElementById.'
The website I want to use doesn't use 'Id=' very much, it mostly uses 'class=' so I cannot use this same method.
I tried swapping the above 'getElementById' for 'getElementsByClassName' however I am getting the answer 'undefined.'
Code:
<html lang="en">
<body>
<p class="para1" > this is the 1st paragraph </p>
<p> <br/> </p>
<p> <br/> </p>
<p> <br/> </p>
<p class="para2" > this is the 2nd paragraph </p>
</body>
</html>
<script type="text/javascript">
var input=document.createElement("input");
input.type="button";
input.value="Check";
input.onclick = showAlert1;
input.setAttribute("style", "font-size:18px;position:absolute;top:100px;right:40px;");
document.body.appendChild(input);//Placement of check button on website;
function showAlert1()
{
alert(document.getElementsByClassName('para2').innerHTML);
}
</script>
getElementsByClassName returns a collection of elements(like an array). So you need to access those using indexes like this:
document.getElementsByClassName("someClass")[0];
//Or if you want to access all
var len = document.getElementsByClassName("someClass").length;
for(var i=0;i<len;i++){
//access like document.getElementsByClassName("someClass")[i]
}
In your case
document.getElementsByClassName('para2')[0].innerHTML
you have to add the script after html tag.
<div class="increased">hi</div> <!-- first specify the tag-->
<script type="text/javascript"> <!-- then call in script-->
var i = 23;
var elems=document.getElementsByClassName("increased");
for(var k = 0; k < elems.length; k++) {
elems[k].style.size = '100px';
}
</script>
Related
I'm still new to Javascript and I'm using the web for research while trying stuff out. I can however not find any reference on how to create an element at a specific index within the text content of an element.
I'm trying to create a highlighting function via JS, and this is what I've ended with so far
let indexes = []
for (i = 0; i < document.body.innerText.length; i++) {
if (document.body.innerText[i] == "`") {
if(document.body.innerText[i - 1] != "\\") {
indexes.push(i)
}
}
}
if (indexes.length % 2 != 0) {
indexes.splice(indexes.length - 1)
}
console.log(indexes)
`body`, \`body`
The idea is to create a wrapping <span> element from the range of the first index to the second, so on..., I'm baisically looking for a JS functin that would allow me to create an element at that specific index.
E.g.
`body` --> <span>body</span> | `Lorem ipsum, dolor` --> <span>Lorem ipsum, dolor</span>
It's probably just a quick hint and not someting major, but thanks anyways!
you can insert an HTML as you would insert a regular string to the innerHTML property.
You can read more about it in here: Inserting string at position x of another string
I share one simple Example to you...
create one test.html
<html>
<head>
<title></title>
</head>
<body>
<h3 id="submited_name"></h3>
<input type="text" name="name" id="name" placeholder="Your Name...">
<input type="submit" id="infosubmit" name="submit" value="Submit" onclick="submit_info()">
</body>
<script type="text/javascript">
function submit_info(argument) {
var name = document.getElementById('name').value;
document.getElementById('submited_name').innerHTML = name;
}
</script>
</html>
for More Learn about the Javascript Refer below websites which I gives,
https://www.w3schools.com/js/default.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript
https://www.tutorialspoint.com/javascript/index.htm
Hello I have a <strong></strong> Tag nested in a paragraph <p></p>, I'm trying to remove the <strong> tag but keep the text or the value. Something similar to unwrapping in jquery but in javascript.
I tried this code on a dummy HTML page and it works fine
<html>
<body>
<p>aaa <Strong>bbbbb</Strong></p>
<p>acccaa <Strong>ddddd</Strong></p>
<p>eeee <Strong>ffff</Strong></p>
<script>
var p = document.getElementsByTagName("p");
for(var i=0;i<p.length;i++){
var strongs = p[i].getElementsByTagName("strong");
for(var j=0;j<strongs.length;j++){
p[i].replaceChild(document.createTextNode(strongs[j].innerText),strongs[j]);
}
}
</script>
</body>
</html>
But as soon as I try the same code on a real page example: https://www.bustle.com/privacy
I get this error:
Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.
Any idea on how to get this to work on the example or any other example?
getElementsByTagName() returns a live NodeList. So when you replace a tag, the indexes of all the following elements shift down and the code fails when you have more than one <strong> tag in the same paragraph. As a result, it will skip some tags.
The solution is to convert the NodeList to an array so it doesn't change while you're looping.
Another problem in your real page that isn't in the snippet is that the <strong> tags can be nested deeply within the <p>. You should use strongs[j].parentElement to get its direct parent, rather than assuming that the p[i] is the parent.
var p = document.getElementsByTagName("p");
for (var i = 0; i < p.length; i++) {
var strongs = Array.from(p[i].getElementsByTagName("strong"));
for (var j = 0; j < strongs.length; j++) {
strongs[j].parentElement.replaceChild(document.createTextNode(strongs[j].innerText), strongs[j]);
}
}
<html>
<body>
<p>aaa
<Strong>bbbbb</Strong> - <strong>12345</strong></p>
<p>acccaa <span><Strong>ddddd</Strong> x</span></p>
<p>eeee
<Strong>ffff</Strong>
</p>
</body>
</html>
You can also avoid the nested loops by using a query selector.
var strongs = document.querySelectorAll("p strong");
strongs.forEach(strong => strong.parentElement.replaceChild(document.createTextNode(strong.innerText), strong));
<html>
<body>
<p>aaa
<Strong>bbbbb</Strong> - <strong>12345</strong></p>
<p>acccaa <span><Strong>ddddd</Strong> x</span></p>
<p>eeee
<Strong>ffff</Strong>
</p>
</body>
</html>
No need to loop through paragraphs to remove <strong>. Simply removing all 'strongs' in place works fine.
function removeStrongs() {
let strongs = document.querySelectorAll('strong');
strongs.forEach(strong => {
strong.insertAdjacentText('afterend', strong.innerText);
strong.remove();
});
}
<h4>This is a <strong>Title</strong></h4>
<p>
Now is the time for all <strong>good</strong> men to come to the <strong>aid</strong> of the party.
</p>
<p>A <strong>quick brown</strong> fox jumps over the lazy dog.</p>
<button onclick="removeStrongs();">Remove Strongs</button>
So in the script tag here I have an array myArr that is printed into p tag in the html:
<html>
<body>
<h1>Header 1</h1>
<div>
<p id="test"></p>
</div>
</body>
</html>
<script>
var myArr = ["abc", 123, "test"];
document.getElementById('test').innerHTML = myArr;
</script>
All that works and is good. So, I have a couple of questions about this, as I'm pretty new to javascript.
I know how to iterate through the array and print out each element within the script tag. But how would I be able to display it into the html? Is there a way to dynamically create the p tags with the element from the array as the contents?
And would I be able to easily add stying into the dynamically created p tag?
Can this kind of thing be done using something like jquery? or another popular simple javascript library?Unfortunately, I will be unable to run a full fledged javascript framework. I am only able to run a basic library.
I attempted a try here:
var my_arr = ["test", "abc", 123];
var arr_length = my_arr.length;
for (i = 0; i < arr_length; i++) {
document.createElement("p");
document.getElementById('test').innerHTML = arr_length;
my_arr[i]
}
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<div id="test">
</div>
You just need to forEach over the array. Inside the callback, create a p, append it to the desired container, and set its textContent to the array element. No frameworks/libraries required:
const test = document.getElementById('test');
const my_arr = ["test", "abc", 123];
my_arr.forEach((item) => {
test.appendChild(document.createElement('p'))
.textContent = item;
});
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<div id="test">
</div>
Array methods are generally preferrable to for loops, but if you really wanted to use a for loop like in your original code, you would have to set the textContent of the created p to my_arr[i], in addition to appending the p to test:
var my_arr = ["test", "abc", 123];
var arr_length = my_arr.length;
const test = document.getElementById('test');
for (i = 0; i < arr_length; i++) {
const p = document.createElement("p");
p.textContent = my_arr[i];
test.appendChild(p);
}
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<div id="test">
</div>
I'm trying to make a simple page that asks you for your name, and then uses name.length (JavaScript) to figure out how long your name is.
This is my code so far:
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
</script>
<body>
</body>
I'm not quite sure what to put within the body tags so that I can use those variables that I stated before. I realize that this is probably a really beginner level question, but I can't seem to find the answer.
You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.
If you want to display a variable on the screen, this is done with JavaScript.
First, you need somewhere for it to write to:
<body>
<p id="output"></p>
</body>
Then you need to update your JavaScript code to write to that <p> tag. Make sure you do so after the page is ready.
<script>
window.onload = function(){
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('output').innerHTML = lengthOfName;
};
</script>
window.onload = function() {
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('output').innerHTML = lengthOfName;
};
<p id="output"></p>
You can create a <p> element:
<!DOCTYPE html>
<html>
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
p = document.createElement("p");
p.innerHTML = "Your name is "+lengthOfName+" characters long.";
document.body.appendChild(p);
</script>
<body>
</body>
</html>
You can create an element with an id and then assign that length value to that element.
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('message').innerHTML = lengthOfName;
<p id='message'></p>
<head>
<title>Test</title>
</head>
<body>
<h1>Hi there<span id="username"></span>!</h1>
<script>
let userName = prompt("What is your name?");
document.getElementById('username').innerHTML = userName;
</script>
</body>
Try this:
<body>
<div id="divMsg"></div>
</body>
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length;
document.getElementById("divMsg").innerHTML = "Length: " + lengthOfName;
</script>
You cannot use js variables inside html. To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html.
The HTML tags that you want to edit is called the DOM (Document object manipulate), you can edit the DOM with many functions in the document global object.
The best example that would work on almost any browser is the document.getElementById, it's search for html tag with that id set as an attribute.
There is another option which is easier but works only on modern browsers (IE8+), the querySelector function, it's will find the first element with the matched selector (CSS selectors).
Examples for both options:
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
</script>
<body>
<p id="a"></p>
<p id="b"></p>
<script>
document.getElementById('a').innerHTML = name;
document.querySelector('#b').innerHTML = name.length;</script>
</body>
You could get away with something as short as this:
<script>
const name = prompt("What's your name?") ?? "";
document.write(`<p>${name.length}</p>`);
</script>
It's not a very clean way of doing it but using document.write is not much worse than calling prompt() as soon as the page loads.
A more user-friendly approach would be to have an actual text input on the page and to dynamically update the length as they type using an event listener.
<label>Name: <input id="name-input"></label><br>
Length: <output id="name-length-output" for="name-input">0<output>
<script type="module">
const nameInput = document.getElementById("name-input");
const nameLengthOutput = document.getElementById("name-length-output");
nameInput.addEventListener("input", e => {
nameLengthOutput.textContent = nameInput.value.length;
});
</script>
If you want to learn how to manipulate pages with JavaScript, the Mozilla Developer Network has a good tutorial about the DOM.
Does anybody knows how can I get all the HTML tags that exist in a page?
I need to get only the tags without their IDs or other attributes, and create a kind of tree-structure of them.
Prefer to do that with Javascript or JQuery.
For example, This HTML code:
<html>
<head>
<title>
Example Page
</title>
</head>
< body>
<h1 style="somestyle">
Blabla
</h1>
<div id="id">
<table id="formid">
<tr>
<td>
</td>
</tr>
</table>
</div>
</body>
</html>
should return return:
html
head
title
body
h1
div
table
tr
td
You can pass a * to getElementsByTagName() so that it will return all elements in a page:
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
// Do something with the element here
}
Its a very simple piece of Javascript
document.querySelectorAll('*')
Try it out in the console log and it will show you all the tags in the document.
Another example is to getElementsByTagName
These do print out into an array, so you can then loop through the elements and doing different things on different elements.
Example:
var items = document.getElementsByTagName("*");
for (var i = 0; i < items.length; i++) {
//do stuff
}
I did it with getElementsByTagName and .tagName for every value in the return array.