Can I get the HTML source of an element with Jquery? [duplicate] - javascript

This question already has answers here:
Get selected element's outer HTML
(30 answers)
Closed 8 years ago.
Rather an odd request, I'm sure, but given a Jquery selector, can I get the raw HTML of an item (and its children) so that I could, for example, put an escaped version of that HTML back on the page?
I'm happy doing the escaping, I've just no idea how to return the HTML from an object.
If there's a simple DOM-standard way of doing this too, I'm just as happy with that.
Edit to addresss the "Oh why didn't you just Google that": Google it. You'll get Jquery's .html() and that will give you the inner HTML of an object. For example, let'sa say you have:
<div id="pants">naughty bits</div>
.html() will only return naughty bits. while the output I'm looking for is <div id="pants">naughty bits</div>

If you have the ID then you can do it like this...
jQuery
$("#ID")[0].outerHTML;
Pure Javascript
document.getElementById("ID").outerHTML;
Using .html() will only get the inner html and not include the element you specify by ID.
Update
There is now also a jQuery method to get the outer HTML of an element...
$("#ID").outerHTML();

Yes, html() method of jquery return html data with all tags as an string:
Example:
Html Source
<div id="DivId">
<p> This is html concept </p>
<br/>
<p> This is jquery concept. </p>
</div>
Jquery Code
var htmlString=$("#DivId").html();
Return Result is:
htmlString:
<p> This is html concept </p>
<br/>
<p> This is jquery concept. </p>

Yes its possible use html()
var source=$('#ID').html()

given a Jquery selector, can I get the raw HTML of an item (and its children)
Get the value using the .html() method:
var htmlOutput = $('#myselector').html();
...so that I could, for example, put an escaped version of that HTML back on the page?
Use the.text() method to set the string as plain text:
$('#anotherselector').text(htmlOutput);
(ie jQuery will fully escape it for you; you don't need to do it manually)

Related

How to take result text when text-overflow property is applied

I have a div with css property text-overflow : ellipsis to add ellipsis and show the text in a single line.
When I perform jquery .text() or .html(), I get the full string, but I need the exact text displaying in the div currently (not the full string).
Can some one guide me how to take the exact displaying string using jquery or JS?
Actual String = "abcdefghijklmnop"
Due to CSS, the div displays "abcd..."
My expected result (using jQuery or JS) "abcd..."
This is not possible without trying to mimic CSS and recreate the strings with the ellipsis using JS.
The reason for this is that CSS only manipulates what is displayed to the user, not the HTML source itself. You can verify this by checking the source code for your document. This means that when you use .text() or .html() you get the values from the DOM, rather than what is displayed via the CSS filter.
There are a couple of hacks that does a pretty good job, but it is still no guarantee that the JS correctly mimics how CSS renders the text.
If you know the number of values you need every time then you can just use JS Like for example if it was always 4 values that gets entered in than it would be like this,
JS Fiddle
form
<form action="" method="post">
<p>
<label for="txt">My txt: </albel>
<input type="text" id="myTxt"><br />
<input type="submit" id="submitButton" value="Send">
</P>
</form>
js
document.getElementById('submitButton').onclick = function() {
myVariable = document.getElementById("myTxt").value;
alert(myVariable.slice(0, 4));
};
No matter what is typed in to the textbox it will be sliced to the first 4 characters.

How to replace text inside specific elements using javascript or any other qualified language?

I have this block of HTML(i don't want to change the code):
<section class="welcome-block-top">
<div class="inside">
<h2>Start a good life</h2>
<label>text to replace 1</label>
<a href="" class="link-a">
some text i do not want to replace</a>
</div>
</section>
i want to replace the text "text to replace 1"
i also want to replace text here:
<h3>
<span>
text to replace 2 </span>
</h3>
please teach me masters, i searched Google and stack-overflow and i dont seem to get something that works in my situation.
Something using the onload js method is preferable because the webpage is dynamically loaded.
if you know a better method to do this with any other language don't hesitate to inform me.
If there is a method to clear the text inside the elements and then insert new text i would be grateful.
You can use JQuery which can easily change the content of the tags.
oldContent = $("div.inside label:first").html();
$("div.inside label:first").html("put your desired content here");
meaining that find first label tag in the div tag having inside class and change its html content with the parameter.
EDIT:
You can of course save the old content and use it.
$("div.inside label:first").html(oldContent + " new content");
or
$("div.inside label:first").append(" new content");
It depends on your real use case but it might be this :
$('*:not(:has(*))').text(function(_,t){
return t.replace("text to replace 1", "replacement")
});
The main idea here is to apply a transformation to the text of all elements with no children (leafs in the DOM tree).
If you have more complex needs, or performance requirements, you might want to have a look at dedicated libraries, like mine : https://github.com/Canop/groumf

Regex using js to strip js from html

I'm using jQuery to sort a column of emails, though they are base64 encoded in js... so I need a regex command to ignore the <script>.*?<script> tags and only sort what is after them (within the <noscript> tags).
Column HTML
<td>
<script type="text/javascript">
document.write(Base64.decode('PG5vYnI+PGEgaHJlZj0ibWFpbHRvOmJpY2VAdWNzYy5lZHUiIHRpdGxlPSJiaWNlQHVjc2MuZWR1Ij5iaWNlPC9hPjwvbm9icj48YnIgLz4K'));
</script>
<noscript>username</noscript>
</td>
Regex that needs some love
a.replace(/<script.*?<\/script>(.*?)/i,"$1");
Assuming that the structure of the html doesn't change, you can use this:
$(a)​.contents().filter(function(){
return this.nodeType === 3
}).eq(1).text();
It gets all text nodes and then filters to the one at index 1 and get's it's text value.
And if you want to stick with regexp, here's one:
a.replace(/(<script type="text\/javascript">[^>]+>|<noscript>.*<\/noscript>)/ig,"");
I know this isn't exactly what you're asking for (though I'm a little confused what you're asking for, to be honest...), but have you looked at using document.getElementsByTagName('noscript')? This function should return an array, the first element of which will be your noscript element.
Also, I'm not really clear on your overall approach to this problem, but it seems like you're misunderstanding the purpose of a noscript element. noscript elements only execute when the browser does not support Javascript, which means the only time noscript content would be displayed to the user is when the Javascript that you're using to modify the noscript content wouldn't run.
Perhaps you could clarify what exactly you're trying to do?

Append custom attributes to a DOM node [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Can I just make up attributes on my HTML tags?
Hi,
I am not sure if what I am asking is even possible, but I'd like to be able to add a custom (nonrendered) propery to an existing HTML DOM node.
For example, if I have a simple DOM as below:
<body>
<p>
<span id="aSpan"></span>
</p>
</body>
.. I'd like to be able to add a custom property to the span 'aSpan' to store a numeric variable.
Is this possible and if so, what is the best way to do it?
Thanks,
Sure, I do this all the time. You can do it in the html:
<span id="aSpan" attname="attvalue">
(validators don't like this though, technically it's not valid html but it works)
Or via javascript:
element.setAttribute('attname', 'attvalue');
You can read it with:
element.getAttribute('attname');
Take a look at the duplicate question for reasons why not to do this this and restrictions on how it can be done legally in HTML 5.
Despite the validation errors you'll receive, using jQuery you can make use of the $.attr() function:
$('.element').attr('foo', 'bar')
I'm not sure in plain Javascript, but jQuery has the data function.
$('#aSpan').data('foo', 69);
alert($('#aSpan').data('foo'));
a simple way.. if your page is dinamic.. you can simply add a value to your ID
a little example if I understand well, you can use it in a class, supposed we have a 56 has ID
<body>
<p>
<span id="aSpan" class="A54F23345A56A23524234"></span>
</p>
</body>
I do simply made a string the ID 'A54F23345A' + 56 + 'A23524234'
But you can use it has you wish.. and the id is hidden from users.. you can use more secure script.. but if isn't a security issue.. it works like a charm ^^
Have a nice day

Strip <script> tags from innerHTML using Prototype

Using Prototype, I'm trying to extract a piece of text from the DOM - this would normal be a simple $().innerHTML job, but the HTML is nested slightly.
<td class="time-record">
<script type="text/javascript">
//<![CDATA[
document.write('XXX ago'.gsub('XXX', i18n_time_ago_in_words(1229311439000)));
//]]>
</script>
about 11 months ago by <span class="author"><strong>Justin</strong></span>
</td>
In this case, innerHTML is going to pick up the JavaScript, which will cause all sort of problems.
What's the best/efficient/fastest way to extract about 11 months ago by <span class="author"><strong>Justin</strong></span> without the JavaScript?
Use innerHTML, and run it through stripScripts:
var html = $$('td.time-record')[0].innerHTML.stripScripts()
That would be useful for grabbing the html of the single cell. A more general solution that does the same but for all td.time-record elements would be:
$$('td.time-record').pluck('innerHTML').invoke('stripScripts');
which would return to you an array of each cell's html (with <script> elements removed) that you could then .join('') or iterate over.
I don't use Prototype's stripScripts or stripTags, as they're trivial, naïve regex hacks that don't get anywhere near handling all possible markup constructs correctly. For a simple case like this you can probably get away with stripScripts, but using these functions for anything security-sensitive is a mistake.
Personally I'd simply remove the script element from the DOM before taking the innerHTML. Once an inline script has been executed there's no reason you need to keep the HTMLScriptElement in the document.
$$('.time-record script').invoke('remove');

Categories