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");
})
Related
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 want this code to replace all ':)'s with my smiley emoji. Although when I run the code I get Uncaught TypeError: Cannot read property 'replace' of undefined at ?v=0.02:10 any help would be greatly appreciated!
Code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>SVG Emoji</title>
</head>
<body>
<script>
var html = document.getElementsByTagName("html").innerHTML;
html.replace(":)", "<img src='https://csf30816.github.io/svg-emoji/emojis/smile.svg'>");
document.getElementsByTagName("html").innerHTML = html;
</script>
<h1>:) Test</h1>
</body>
</html>
Replace
document.getElementsByTagName("html").innerHTML
with
document.getElementsByTagName("html")[0].innerHTML
as getElementsByTagName returns an array.
Also, the string.replace() method returns a new string without mutating / modifying the given one. You would need to re-assign the returned string to html = html.replace(...).
Also, you need to move your <script> to the bottom. Otherwise it can't access DOM elements that appear beneath it in your HTML document, such as the <h1> element:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>SVG Emoji</title>
</head>
<body>
<h1>:) Test</h1>
<script>
var html = document.getElementsByTagName("html")[0].innerHTML;
html = html.replace(":)", "<img src='https://csf30816.github.io/svg-emoji/emojis/smile.svg'>");
document.getElementsByTagName("html")[0].innerHTML = html;
</script>
</body>
</html>
See also How to get the <html> tag HTML with JavaScript / jQuery?
For a more robust approach to replacing text within the DOM see jQuery replace all occurrences of a string in an html page
Your code and the problem you are trying to solve are doing different things. This will give you the solution you are seeking, i.e. replace all ':)'s with my smiley emoji
function replaceTextByImage(pattern, src) {
document.body.innerHTML = document.body.innerHTML.replace(
new RegExp(pattern, 'g'),
'<span style="background-size: 100% 100%; background-image: url(\'' + src + '\');">    </span>'
);
}
replaceTextByImage(':\\)', 'https://csf30816.github.io/svg-emoji/emojis/smile.svg');
replaceTextByImage(':P', 'https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/svg/1f61b.svg');
replaceTextByImage(':D', 'https://what.thedailywtf.com/plugins/nodebb-plugin-emoji-one/static/images/1f603.svg');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<p>
Hello World! How are you? :). Do you like this emoji :)
</p>
<div style="font-size:50px;">How about now :)</div>
<div style="font-size:25px">You can also do this :P and this :D now!</div>
</body>
</html>
PROS
Emoji will resize according to font used.
Replaces all occurrences of a pattern
CONS
If you have an inline script in the body of your html, it may be re-executed every time the function replaceTextByImage is called because it is setting the body's innerHTML.
If you want to use jquery then don't read this answer.
But for those who can allow their script not be jquery,
Here is your code.
document.getElementsByTagName("H1")[0].innerHTML = '<img src="https://csf30816.github.io/svg-emoji/emojis/smile.svg">';
<h1>:) Test</h1>
What the problem is:
You are returning an array.
Use one element with [0]:
document.getElementsByTagName("html")[0].innerHTML = html;
I really cannot understand why this does not work. I've tried couple of tricks but I just don't get it.
<html>
<head>
<script type="text/javascript">
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
</script>
</head>
<body>
<div id="results">
hey there
</div>
</body>
</html>
This is working as you can see here:
http://jsfiddle.net/gHbss/
It's important that you put the JavaScript after your HTML div container.
The problem that you're facing is that the browser runs the JavaScript as it's encountered when rendering/processing the page. At this point it will alert() your message, but the relevant element, the #results div isn't present in the DOM, so nothing can be changed.
To address this, you can either place the script at the end of the page, just before the closing </body> tag, or run the code in the onload event of the body or window.
The script has to be placed after the div#results or executed onload, otherwise the element is still unknown when you try to access it.
You need to call this script in onload event
i.e
window.onload=function(){
//your code
}
<html>
<head>
<script type="text/javascript">
function onloadCall()
{
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
}
</script>
</head>
<body onload="onloadCall()">
<div id="results">
hey there
</div>
</body>
</html>
Hope the above snippet shows you the fix
i use that tag to alert me when a tag has been shows up
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
<iframe></iframe>
</body>
</html>
strange , since this code working :
<html>
<head>
</head>
<body>
<iframe></iframe>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
</body>
</html>
why the Js need to under the tag to work?
what's the problem here?
Because the code in a script tag is executed immediately. And in the first example the iframe doesn't exist at that time. But what you can do is to wrap you code into an onload (for the main page) event. E.g.:
window.onload = function() {
//your code
}
Then it doesn't matter where the code is placed.
Iframe tag does not exist at the moment you are trying to access it.
You may check that by simply alerting array length, like
alert(document.getElementsByTagName('iframe'));
Have you thought about executing your javascript after the page is loaded? You may use some frameworks like jQuery to facilitate crossbrowser issues. Or just put all your javascript code to the very bottom of body.
I want to replace the current script tag with the HTML contents generated by the same script.
That is, my Page is
<html>
<body>
<div>
<script src="myfile1.js"></script>
</div>
<div>
<script src="myfile1.js"></script>
</div>
</body>
</html>
Inside each .js file corresponding html contents are generated. I want to put the contents as the innerHTML of the parent div. But can't set id for the parent div because the page is not static. So the current script tag must be replaced with the HTML content. How can I do this?
For each script tag src is the same. So can't identify with src. These scripts displays
some images with text randomly. Scripts are the same but displays different contents in divs on loading
Please help me
try inside of myfile1.js:
var scripts = document.getElementsByTagName( "script" );
for ( var i = 0; i < scripts.length; ++ i )
{
if ( scripts[i].src == "myfile1.js" )
{
scripts[i].parentNode.innerHTML = "new content";
}
}
This is a great question for those trying to implement a JSONP widget. The objective is to give the user the shortest possible amount of code.
The user prefers:
<script type="text/javscript" src="widget.js"></script>
Over:
<script type="text/javscript" src="widget.js"></script>
<div id="widget"></div>
Here's an example of how to achieve the first snippet:
TOP OF DOCUMENT<br />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
// inside of widget.js
document.write('<div id="widget"></div>');
$(document).ready(function() {
$.getJSON('http://test.com?remote_call=1', function(data) {
$('#widget').html(data);
});
});
<br />BOTTOM OF DOCUMENT
Have a look at: http://alexmarandon.com/articles/web_widget_jquery/ for the correct way to include a library inside of a script.
document.currentScript has been available since 2011 on Firefox and 2013 on Chrome.
document.currentScript documentation at MDN
<!DOCTYPE html>
<meta charset="UTF-8">
<title>currentScript test</title>
<h1>Test Begin</h1>
<script>
document.currentScript.outerHTML = "blah blah";
</script>
<h1>Test End</h1>
Unfortunately a running JavaScript file is not aware of where it is running. If you use document.write() in the script, the write function will take place wherever the script runs, which would be one way to accomplish what you want, but without replacing the contents or being able to perform any actions on the enclosing DIV.
I can't really envisage a situation where you'd have such stringent restrictions on building a page - surely if the page is dynamic you could generate identifiers for your DIV elements, or load content in a more traditional manner?
Why not use Smarty?
http://www.smarty.net/
You can use javascript in Smarty templates, or just use built-in functions.
Just take a look at http://www.smarty.net/crash_course
poof -- old answer gone.
Based on your last edit, here's what you want to do:
<html>
<head>
<!-- I recommend getting this from Google Ajax Libraries
You don't need this, but it makes my answer way shorter -->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function getRandomContent(){
// I expect this is the contents of your current script file.
// just package it into a function.
var rnd = Math.random();
return "[SomeHtml]";
}
$('.random').each(idx, el){
$(this).html(getRandomHtmlContent());
});
});
</script>
</head>
<body>
<div class="random">
</div>
<div class="random">
</div>
</body>
</html>
If you don't mind the script tag remaining in place you can use something as simple as document.write().
myfile1.js:
document.write("<p>some html generated inline by script</p>");
It will do exactly what you need.