for(i=0;i<headingsallowed.length;i++){
var x=allhtml.getElementsByTagName(headingsallowed[i]);
}
I have this code which gets all the headings in my scripts, I want to process them one by one and output the title that is in each of the headings. headingsallowed is the array with the headings in so just ['h1,'h2','h3']. allhtml is just var allhtml = document.getElementById('content');
SO
<h1>hi</h1>
<h1>he</h1>
<h1>yes</h1>
<h1>no</h1>
would output hi,he,yes,no
I tried x.innerHTML and x.text but they did not work
For the given html, the following will print the content inside each heading.
var headings = document.getElementsByTagName('h1');
for(i=0;i<headings.length;i++){
console.log(headings[i].innerHTML);
}
If I understood your problem properly. I got this working.
HTML
<h1>hi</h1>
<h1>he</h1>
<h1>yes</h1>
<h1>no</h1>
Javascript
var allHeadings=document.getElementsByTagName('h1');
for(i=0;i<allHeadings.length;i++){console.log(allHeadings[i].innerHTML)}
Related
Is this possible, and if so how is it done?
I do not want to use iframes.
I want to write the html of just a div in a separate file. I want to then insert this into my body of my html.
I then want to write a separate js file which operates the code in the div.
So my html file would look like this:
mydivhtml.html (It is just this html, no headers or body etc)
<div id="mydivhtml" style="width: 30vw; height: 100vh;">
<button id="myButton" onclick="MyOnClick();"></button>
<label id="myLabel"></label>
</div>
My js file would be a normal js file:
mydivjs.js
function MyOnClick(){
document.getElementById("myLabel").innerHTML = "Hello";
}
Then when I wanted to use this, I include the js file as normal:
<script type="text/javascript" src="mydivjs.js"></script>
But, then I just add the html in some way.
I know people advise not to do document.body.innerHTML = document.body.innerHTML + "<div>Hello!</div>"; because it will keep on firing onload.
So I want to do something like this:
var myDiv = document.createElement("div");
myDiv.id = 'mydivhtml';
myDiv.innerHTML = "<button id=\"myButton\" onclick=\"MyOnClick();\"></button>"
"<label id=\"myLabel\"></label>";
document.body.appendChild(myDiv);
BUT how do you do this from just the mydivhtml.html without having to write it out bit by bit?
So if your directories is like this
Main -|
|main.html
|mydivhtml.html
|mydivjs.js
then you should have this code on your main.html
<script>
fetch("./mydivhtml.html").then(x=>x.text()).then(data =>{
var myDiv = document.createElement("div");
myDiv.id = 'mydivhtml';
myDiv.innerHTML = data;
document.body.appendChild(myDiv);
// need to have mydivjs.js as a script
var mydivjs = document.createElement("script")
mydivjs.src ="./mydivjs.js"
myDiv.appendChild(mydivjs)
})
</script>
hope it works...
I have some js code that has been imported from another file which has a variable in it I want to update in my HTML file. How can I update the variable without pasting the js code into my HTML file?
JS (script.js):
var link = "https://example.com"
var codeBlock = `...some html code... ${link} ...some more html code`;
document.getElementById("div").innerHTML = codeBlock
HTML:
<div id="div"></div>
<script src= "script.js"></script>
<script>
//I want to change this variable
var link = "https://anotherexample.com"
</script>
On line one of your code, you declare link and give it a value.
On line two, you use that value.
You can't change link later on and affect what happened when the value was read and used in the past.
If you want to change the final result, then it is the final result you have to change (i.e. you need to assign a new value to document.getElementById("div").innerHTML).
You are getting the value but not setting it to the variable that the HTML is showing.Is this you are looking for :
var updatedLink = document.getElementById("anotherlink").innerHTML;
var codeBlock = `...some html code... ${updatedLink} ...some more html code`;
document.getElementById("div").innerHTML = codeBlock
<div id="div"></div>
<div id="anotherlink" style="display:none"></div>
<script src= "script.js"></script>
<script>
var link = "https://anotherexample.com";
document.getElementById("anotherlink").innerHTML = link
</script>
Your script is working and the variable is being changed. If you console.log(link) after declaring it again, you'll see the variable has changed. If you're expecting the script to execute again, that won't happen without calling it again.
What you may want to try is iterating through the document looking for something to trigger that statement, for example, links in the document.
const links = document.querySelectorAll('a');
var href = [];
links.forEach(link => href.push(link.href));
var codeBlock = '';
href.forEach(link => {
if (link == "https://stacksnippets.net/anotherexample.com") {
codeBlock = `...some html code... ${link} ...some more html code`;
document.getElementById('div').innerHTML = codeBlock;
}
})
<div id="div">link</div>
Or without checking for a specific URL:
const links = document.querySelectorAll('a');
var href = [];
links.forEach(link => href.push(link.href));
var codeBlock = '';
href.forEach(link => {
codeBlock = `...some html code... ${link} ...some more html code`;
document.getElementById('div').innerHTML = codeBlock;
})
<div id="div">link</div>
I want to convert the following string to HTML tags and place it inside my div.
<strong>asdfadfsafsd</strong>
I am using the following code to place it inside my div:
var message = "<strong>testmessage</strong>";
document.getElementById('message').innerHTML = bericht;
The problem is that I see the following in my div now:
<strong>testmessage</strong>
But I want to see:
testmessage
What is the problem?
var string = "<strong>asdfadfsafsd</strong>",
results = document.getElementById("results")
results.innerHTML = string;
results.innerHTML = results.textContent;
<div id="results"></div>
At first load the it as html. Then fetch it as text and then again load it as HTML :)
Refer HTML Entities
Try createElement
var tag = document.createElement("strong");
var t = document.createTextNode("testmessage");
tag.appendChild(t);
document.body.appendChild(tag);
I have a string of HTML like this
var html = "<html><head></head><body class='getMe'></body></html>";
I want to get the body tags class and I tried doing that like this.
$(html).filter("body").attr("class")
$(html).find("body").attr("class");
But both methods return undefined. Any help?
You do not need to parse into html, rather try RegExp:
var html = "<html><head></head><body class='getMe'></body></html>";
var clazz = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1]; //getMe
Here, String.match() gives array of string for given pattern.
body\sclass=['|"]([^'|"]*)['|"] gives ["body class='getMe'", "getMe"]. Using (), you can grab a particular group.
Also works with multiple classes and other attributes:
var html = "<html><head></head><body class='getMe hey there' id='xyz' bgcolor='red'></body></html>";
var clazz = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1]; //getMe hey there
Edited
In order to get classes belonging to body tag starting with header-:
var html = "<html><head></head><body class='getMe header header-1 header-two test'></body></html>";
var headers = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1].match(/(header\-\w+)/g);
//["header-1", "header-two"]
Try
var html = "<html><head></head><body class='getMe'></body></html>";
var className = $("<html />", {"html":html}).find("body")[0].className;
console.log(className);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
Did you try to put it in a Variable? find the tag without ""
var MyClass = $(body).attr("class");
// or $(html).find(body).attr("class");
I'm working on a form builder website. After a form is built it must be saved in database. When the user clicks on a form name from the list of saved forms the form information is restored from database. One of the variables I will restore is the structure of the form. In javascript I wrote these lines of code:
var prefix_content='<!DOCTYPE HTML>\n<html lang="en-US">\n<head>\n<meta charset="UTF-8">\n<title> </title>\n </head>\n<body>\n ';
var sufex_content=' \n</body></html>';
var dynamic_content=String(text_content);
document.write(prefix_content + dynamic_content + sufex_content );
The variable dynamic_content contains the dynamic structure.
The problem is that prefix_content and sufex_content is displayed as html but dynamic_content is written in the page as text. Any one knows why is that or knows how to solve this problem.
Note: when I write the text in dynamic content statically between single quotes it is displayed as html not text.
If you're seeing the content retrieved from your database as plaintext, instead of HTML, its HTML entities are probably getting escaped somewhere along the way. Check the contents of your text_content variable (e.g. use console.log(text_content) and if you're seeing stuff like <div> instead of <div>, go on and find out where your escaping happens and either remove it or manually unescape.
TRY THIS:
var prefix_content='<!DOCTYPE HTML>\n<html lang="en-US">\n<head>\n<meta charset="UTF-8">\n<title> </title>\n </head>\n<body>\n ';
var sufex_content=' \n</body></html>';
var dynamic_content=String(text_content);
var parser = new DOMParser();
var el = parser.parseFromString(dynamic_content, "text/html");
document.write(prefix_content + el + sufex_content );
Or you can try this too: Using jQuery
var dynamic_content=String(text_content);
var el = $.parseHTML( dynamic_content );
document.write(prefix_content + el + sufex_content );
var content = "<div style='color:red;'>TEST</div>";
var prefix ='<!DOCTYPE HTML>\n<html lang="en-US">\n<head>\n<meta charset="UTF-8">\n<title>TEST</title>\n</head>\n<body>\n';
var suffix ='\n</body></html>';
var all = prefix + content + suffix;
var parser = new DOMParser();
var doc = parser.parseFromString(all, "text/html");
console.log(doc.children[0].outerHTML);
Instead of children[0] you can also go for:
doc.documentElement.outerHTML
Results in:
<html lang="en-US"><head>
<meta charset="UTF-8">
<title>TEST</title>
</head>
<body>
<div style="color:red;">TEST</div>
</body></html>