Append custom attributes to a DOM node [duplicate] - javascript

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

Related

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

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)

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?

Fill forms in JavaScript

I'm currently a student in Software Engineering, and I'm trying to create a small program (I don't know if the word "macro" is appropriate for it) in HTML or JavaScript, to fill a form from a webpage.
The webpage has the following code, placed in the head section:
input type=password name=code size=8 maxlength=8
input type=password name=nip size=8 maxlength=8
input type=password name=naissance size=8 maxlength=8
I've been thinking of maybe using JQuery, as I've browsed a little bit on the internet to figure out how to do it, but I don't really know how to do that. I'm pretty sure the only way to do it is to modify the values of the fields "code", "nip" and "naissance", but how do I get access to them from an external file?
Please note that I have bases in HTML and JavaScript, but nothing amazing - I'm still learning :/
Since you're looking to use jQuery, this might be a good place to start:
http://api.jquery.com/attribute-equals-selector/
Next might be a good tutorial in jQuery to get you started. I'm going to assume you can find those on your own, and I'm going to jumpstart your work:
var selector = 'input[name="code"]'; // <-- we define the element we want to find here
// we will use that to select a jQuery element like this --> $(selector)
$(selector).val('CODE!!'); // <-- it's just that easy to set a value.
So if that's what it takes to set the value for code from javascript, you can guess what the other two would look like. I'll give you a hint on the second one:
$('input[name="nip"]').val('NIP!!');
Of course, all this assumes you do use jQuery in the browser to accomplish this
I believe what you are looking for is simply accessing the fields from javascript. You can include any external javascript on the HTML page:
<html>
<head>
<script src="http://someexternalurl.com/js/jsfile.js" type="text/javascript"></script>
...
Then in this javascript file you can access the elements as:
alert(document.getElementByName("nip").value);
document.getElementByName("nip").value = "abc";
Hope that helps.
You can accomplish you project by going through this links
w3school
tizag
jqueryui
jquery
Go through this links
with regards
Wazzy

How to insert text into a form with JavaScript

I'm trying to create a simple extension for personal use. It's partially from laziness, and partially from an urge to learn. I've never made extensions before, but I've been looking at the documentation. Now I just need to write the code. What I'm trying to do, is when the browser loads a certain page, to insert text into a specific form. The form is as follows
<div id="set_tags" class="advanced_option">
<label for="post_tags" class="inline_input_label" id="post_tags_label"
onclick="Element.remove($(this))"
style="left:8px; right:auto; text-align:left">tags</label>
<input id="post_tags" name="post[tags]" type="text"/>
</div>
I haven't worked much with javascript, so is there a way to add the text "Music" to this when the page is loaded?
You can use the onload function to start your function.
http://javascript.about.com/library/blonload.htm
Since you are new to javascript you may want to get familiar with unobtrusive javascript (http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html) which I find is a better way to write javascript, as you can then easily comment out javascript and see how it works when that is disabled. But, it would be easier to learn this in the beginning.
To get the input tag you can use document.getElementById() which would be something like:
var elem = document.getElementById('post_tags');
Then, to add text to this field there should be a value property in your input definition above, and you would just do:
elem.value = "Music";
document.getElementById("post_tags_label").appendChild(
document.createTextNode("Music"));
I'm assuming that you want to put it at the end of the element post_tags_label.
This is really easy to do if you use GreaseMonkey. It's perfect for personal changes you want to make to web pages, etc.

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