I want to replace the content in the current element with and html string taken out of an object.
It has to work dynamically regardless of what div, p...etc it is in.
<div id="content">
<h5><script>$(this).append(en.login_terms_and_conditions);</script></h5>
</div>
It's possible to do what you've shown, but it's probably not a good idea. You'd use $(document.body.lastElementChild):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
// Presumably you have something defining that `en` variable and the object it refers to:
var en = {
login_terms_and_conditions: "terms and conditions here"
};
</script>
<p>one</p>
<p>two</p>
<p>three</p>
<div id="content">
<script>$(document.body.lastElementChild).html(en.login_terms_and_conditions);</script>
</div>
<p>four</p>
<p>five</p>
<p>six</p>
...or of course, just $("#content") if that id is always on the element.
This works because the element is added to the DOM as of when your script runs (the details on that are complicated, but covered in the spec), even though the element's end tag has not yet been parsed.
I wouldn't do that, though, for a couple of reasons, not least that if you're doing this with jQuery, you have to load jQuery prior to that element, which holds up the rendering of your page. You could fix that by not using jQuery for this bit:
<script>
// Presumably you have something defining that `en` variable and the object it refers to:
var en = {
login_terms_and_conditions: "terms and conditions here"
};
</script>
<p>one</p>
<p>two</p>
<p>three</p>
<div id="content">
<script>document.body.lastElementChild.innerHTML = en.login_terms_and_conditions;</script>
</div>
<p>four</p>
<p>five</p>
<p>six</p>
...but it still seems like there are simpler solutions, like just document.write-ing the content, or using server-side templating.
Your example is not quite how jQuery works. The location of the script is irrelevant to the scope of this when attempting to affect an element.
Instead you need to select the #content element directly, then call html() with the value of the login_terms_and_conditions property. Try this:
var en = {
login_terms_and_conditions: '<h2>fizz buzz</h2>'
}
$(function() {
$('#content').html(en.login_terms_and_conditions);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<h5>foo bar</h5>
</div>
First, this does not work as you want. You have to select an element first and then refer to it with this.
Second, even if you would want to add an object key directly into html, that's not possible. ( is possible in JSX but that's another thing :) ).
Third, to make it more dynamic (as I understood you want), you can add some specific data-attributes to your html elements. For example a data-obj='content' for the content and so on. Then, you can iterate your en object and add en[key] value to it's respective html element with the data-obj.
See below
const en = {
title: 'Title in english',
content: 'Some content in english here <br/>Some content in english here ',
link: 'Link text'
}
for (let key in en) {
if( en.hasOwnProperty(key) ) {
let element = $(`[data-obj='${key}']`)
element.html(en[key])
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<h5 data-obj="title"></h5>
<p data-obj="content"></p>
<a data-obj="link"></a>
</div>
If you want to target by id, then you could try something like this:
$("#content").html(en.login_terms_and_conditions);
Related
I feel uncomfortable having to create elements scattered everywhere and change them one by one when variable is changed.
<div>
<div class="element-1"></div>
<div class="element-2"></div>
</div>
<script>
var e1= "";
var e2= "";
SomeEvent.trigger(function(){
e1= "this is content of element-1";
e2= "this is content of element-2";
});
$("value of e1").change(function(){
$(".element-1").html(e1);
});
$("value of e2").change(function(){
$(".element-2").html(e2);
});
</script>
Can I do something like it only with js or jQuery?
<div>
{{e1}}
{{e2}}
{{e3}}
</div>
And {{e?}} is binding with e?. It show e?'s value and change everywhere e? changes. Thanks.
Use mustache and place your {{varibles}} in the template then pass data to them.
When I reload my browser to show some json data the JavaScript code keeps replacing my HTML code? How can I correct the problem?
JavaScript code:
$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data) {
document.write(data.title);
};
HTML Code:
<div class="container">
<div id="json_example">
<h1>json Example</h1>
</div>
</div>
Don't use document.write() as it replaces fully built HTML documents with the new content. document.write() should only ever be used to construct dynamic pages while the page is being built.
Instead, just populate some pre-existing element with data.title,
As in:
$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data) {
$("#output").text(data.title);
};
<div class="container">
<div id="json_example">
<h1>json Example</h1>
<span id="output"></span>
</div>
</div>
You are using document.write() which takes your document, and replaces it's content with the content you supply to the function. If you want to replace just the content of the <div id="json_example"></div> element, then you can use the following snippet in place of the document.write():
$("#json_example").text(data.title);
For non jQuery-version:
document.querySelector("#json_example").innerText = data.title;
If you want to replace the content of the <h1> the correct selector would be #json_example h1 instead.
In all the snippets what you do is find the element you want to change the content of using a CSS-selector. Both jQuery and pure Javascript supports this since IE8.
After finding the correct element, you set the elements content text to the content you want.
NOTE! Do NOT use innerHtml or .html() to set the content, as that opens you to script injections. Only use those methods when you generate the HTML yourself on the fly, in the browser. Even your database needs to be considered dirty.
try this
$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data) {
document.getElementById("json_example").textContent = data.title;
};
Since you're already using jQuery here's a possible solution which uses it.
$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data) {
$("#json_example").html("<h1>" + data.title + "</h1>");
};
This replaces your div html with your content.
I have a very basic question about using the "this" keyword to retrieve a DOM element.
Consider the following HTML/Javascript:
<div class="container">
<div class="regular-div">
<script type="text/javascript">
console.log(this);
</script>
Here is a div withOUT onclick
</div>
<div class="onclick-div" onclick="console.log(this)">
Here is a div with onclick
</div>
</div>
While clicking the "onclick-div" it does return the DOM object for that div. However, the console.log event calls 'this' indirectly in the "regular-div" and returns window.
Is it possible to get "this" DOM object when 'this' is called indirectly? My purpose is I want to fire a function in line in the HTML, but need to send the function "this". Here's an example of what i'm trying to do:
<div class="container">
<div class="regular-div">
<script type="text/javascript">
loadSomeHTML(this, varA, varB, varC);
</script>
</div>
</div>
Thanks everyone for any clarification of how "this" works in the above context.
In your first example, the script isn't in any way associated with the div. It's just been output within the div, but it's not connected to it. The script runs as the page is being parsed.
Is it possible to get "this" DOM object without a user interaction?
If you mean inline with the parsing of the HTML, you could do this:
<div class="container">
<div class="regular-div">
Here is a div withOUT onclick
</div>
<script type="text/javascript">
(function() {
var list = document.querySelectorAll('div');
console.log(list[list.length - 1]);
})();
</script>
</div>
Note that the script tag is immediately after the ending </div> tag for the div you're trying to target. The script gets what's currently the last div in the document as of when the script runs. Or of course you could identify the div in some way (a class, for instance) and use that (and then potentially remove it so you could do it again later in the document).
It looks dodgy, but it's perfectly valid cross-browser, and was even recommended at one stage by the Google Closure Library engineers.
Live Example:
<div class="container">
<div class="regular-div">
Here is a div withOUT onclick (look in console for result)
</div>
<script type="text/javascript">
(function() {
var list = document.querySelectorAll('div');
console.log(list[list.length - 1]);
})();
</script>
</div>
Example using a class we move:
<div class="container">
<div class="target-me">
The first div
</div>
<script type="text/javascript">
(function() {
var div = document.querySelector(".target-me");
div.classList.remove("target-me");
console.log(div);
})();
</script>
<div class="target-me">
The second div
</div>
<script type="text/javascript">
(function() {
var div = document.querySelector(".target-me");
div.classList.remove("target-me");
console.log(div);
})();
</script>
</div>
Note I didn't use id, because if we used an id and JavaScript wasn't enabled, we'd end up with an invalid document (because it would have multiple elements with the same id). It'd be fine if JavaScript were enabled (because we'd remove the id from earlier ones before later ones were created), but...
Javascript has no implicit connection to the HTML DOM. The reason why onclick works the way you want is because the HTML DOM implementation passes the element to the js callback. You need to do something similar in your other case. One way to do this is:
<div class="container">
<div class="regular-div" id="mydiv">
<script type="text/javascript">
loadSomeHTML("#mydiv", varA, varB, varC);
</script>
</div>
</div>
Then your js implementation does the lookup to find the element:
function loadSomeHTML(selector, varA, varB, varC) {
var el = document.querySelector(selector);
// now el is where you want to insert your HTML
// ...
}
The code inside the script tag doesn't have any connection with the tag itself. this should, basically, return the object on which the current function was called, or the global environment, window. In the first div, the code is just executed, on no object, so window is returned. The value of onclick, on the other hand, is treated as a function (with even some parameters, like e), that gets called on the element with the attribute. So, the code in the script element is executed in the global scope, whereas the one in the attribute is in a function scope (that's why all vars are shared across script tags).
As explained in How may I reference the script tag that loaded the currently-executing script?, the proper way of obtaining a reference to the script element whose code is being executed is
document.currentScript;
Then, to get the parent node of that element, use
document.currentScript.parentNode;
<div class="container">
<div id="regular-div">
<script type="text/javascript">
alert('#' + document.currentScript.parentNode.id);
</script>
Here is a div withOUT onclick
</div>
</div>
just having some issues with this jQuery thing.
What i'm trying to do is:
i have some audio control buttons that look like this:
<p>Play audio</p>
but there are too many on the page so i'm trying to optimise the code and make a little function that checks for the div id on the button and adds tells the player what track to play.
so i've done this:
<div id="audioControlButtons-1">
<div class="speaker"> </div>
<div class="play"> </div>
<div class="pause"> </div>
</div>
<script>
$(document).ready(function() {
$("[id^=audioControlButtons-] div.play").click(function() {
var id = new Number;
id = $(this).parent().attr('id').replace(/audioControlButtons-/, '');
//alert(id);
player1.loadAudio(id);
return false;
});
});
</script>
my problem is:
the id is not passing to the the player1.loadAudio(id)
if i hardcode player1.loadAudio(1)
it works! but the moment i try to pass the variable to the function it doesn't work...
however if you uncomment the alert(id) thing you will see the id is getting generated...
can someone help?
cheers,
dan
I think I see your problem. The variable id is a string. Try;
player1.loadAudio(parseInt(id));
Yah and the initialise line isn't necessary. Just use;
var id = $(this).parent().attr('id').replace(/audioControlButtons-/, '');
I'm actually kind of confused with your example because you originally have this:
<p>Play audio</p>
but then you don't reference it again. Do you mean that this html:
<div id="audioControlButtons-1">
<div class="speaker"> </div>
<div class="play"> </div>
<div class="pause"> </div>
</div>
Is what you are actually creating? If so, then you can rewrite it like this:
<div class="audio-player">
<div class="speaker"> </div>
<div class="play" data-track="1"> </div>
<div class="pause"> </div>
</div>
Then in your script block:
<script>
$(document).ready(function() {
$(".audio-player > .play").click(function() {
var track = $(this).data('track');
player1.loadAudio(+track);
return false;
});
});
</script>
So a few things are going on here.
I just gave your containing div a class (.audio-player) so that it's much more generic and faster to parse. You don't want to do stuff like [id^=audioControlButtons-] because it is much slower for the javascript to traverse and parse the DOM like that. And if you are going to have multiples of the same element on the page, a class is much more suited for that over IDs.
I added the track number you want to the play button as a data attribute (data-track). Using a data attribute allows you to store arbitrary data on DOM elements you're interested on (ie. .play button here). Then this way, you don't need to this weird DOM traversal with a replace method just to get the track number. This saves on reducing unnecessary JS processing and DOM traversing.
With this in mind now, I use jQuery's .data() method on the current DOM element with "track" as the argument. This will then get the data-track attribute value.
With the new track number, I pass that along into your player1.loadAudio method with a + sign in front. This is a little javascript trick that allows you to convert your value into an actual number if that is what the method requires.
There are at least a couple of other optimizations you can do here - event delegation, not doing everything inside the ready event - but that is beyond the scope of this question. Hell, even my implementation could be a little bit optimized, but again, that would require a little bit more in depth explanation.
How do I retrieve the content between and including the following <div class="adding"> and store it in a variable?
<div class="adding">
<b>
<div class="column">
<div class="mediumCell">
<input type="text" name="name" placeholder="توضیح" title="نام پکیج تور خارجی">
</div>
</div>
<div class="column" style="margin: 5px 3px;">
<div class="mediumCell">
<div class="adda">
</div>
</div>
</div>
</b>
</div>
var adding = '<div class="adding"><b><div class="column"><div class="mediumCell"><input type="text" name="name" placeholder="توضیح" title="نام پکیج تور خارجی"></div></div><div class="column" style="margin: 5px 3px;"><div class="mediumCell"><div class="adda"></div></div></div></b></div>'
In each click I want to get the content just once.
Unfortunately, after two or more clicks getting content several times together (E.x: after two clicks it stores the content twice).
I tried this:
$(function () {
var i = $('.adding').size();
$('.add_input').live('click', function () {
var scntDiv = '.' + $(this)
.closest('.find_input')
.find('div')
.attr('class');
var input = $(scntDiv).html();
$(this).remove();
$(input).appendTo(scntDiv);
i++;
return false;
});
});
You can use the html() method, as others have said, but there's a catch: that method returns the inner HTML content of the element, so the markup of the outer <div> element won't be included in the result.
Since you seem to want that markup, you can work around the issue with clone(), wrap() and parent():
var adding = $("div.adding").clone().wrap("<div>").parent().html();
You can get the inner HTML using the html function:
var adding = $(".adding").html():
...which will give you the browser's version of the markup within the first matching div (the first div with the class "adding"). It's fairly simple at that point to wrap it with the markup for the div, unless there are a lot of chaotic attributes involved.
However, note that the markup you get back may not be what you expect, because your HTML is invalid. b elements cannot contain div elements (b elements may only contain phrasing content; div elements are flow content), and so the browser adjust things as it sees fit to display something reasonable. This is a Bad Thing(tm), it's much better with dynamic web apps to ensure that your HTML is valid.
Is that what you're asking for ?
var adding;
$('.adding').click(function(){
adding = $(this).html();
alert(adding);
});
var adding = $(".adding").html();
maybe?