Edit: Everyone went on all kinds of tangents, but the question remains - how do I get an attribute of an html element inside an angular controller?
Here is a plnkr attempt: http://plnkr.co/edit/0VMeFAMEnc0XeQWJiLHm?p=preview
//$scope.myElem = angular.element('testDiv'); //this breaks angular
$scope.myElem = $document.find('testDiv'); //this doesn't break angular, but unclear what it returns
$scope.myAttr = $scope.myElem.name; //this returns nothing
If you need convincing that this is actually necessary - I need to find when a user scrolls through a div, as is shown here: http://jsfiddle.net/rs3prkfm/ Note that this has nothing to do with the question, simply a scenario. The question is simple - how do I get an attribute's value?
References:
Useless official docs: https://docs.angularjs.org/api/ng/function/angular.element
The only useful link that still doesn't work: http://mlen.io/angular-js/get-element-by-id.html
You could use the element api https://docs.angularjs.org/api/ng/function/angular.element
There should be only very few occasions where you would really need it, though.
You should manipulate the DOM using directives. The controller should only manipulate the data of the application and offer it to the html.
If you have direct manipulation on the Controller you can't, for example, bind several views to the controller. Also, if you change the id of one tag in the html and you are manipuling it directly in you controller, the controller will break.
Read this:
http://ng-learn.org/2014/01/Dom-Manipulations/
Hope it helps.
Use angular.element:
var myElem = angular.element("#testDiv"); // here you get your div
var myAttr = myElem.attr("name"); // you get: "testDiv"
Remember you have limitations using jqlite. If you want full functionallity of jquery element, import a full "jquery.js" before importing your angular script.
However, to manipulate the DOM you SHOULD use directives as stated by most of the answers.
Related
I want to place my templates on several places in the DOM without having to write the jQuery expression over and over again. I want to place my template in the DOM by just typing the variable/attribute {{template}} anywhere in the body.
Is this doable using Handlebars? If not, is there any other way for me to achieve this?
You need to use HandleBar helpers
handlebar_helpers
p.s. dont forget to use safestring else it will be escaped by default
Updating with answer based on ur comment
The link i provided did give out an excellent explanation. However please find below an example.
Assume your need to return a welcome message when a name is given
Handlebars.registerHelper('welcome', function(name) {
return new Handlebars.SafeString(
"<p>Hi "+name+", welcome to stackoverflow</p>"
);
});
Then calling
{{{welcome "sagittarius"}}} will return
Hi sagittarius, welcome to stackoverflow
So, I have some code that should do four things:
remove the ".mp4" extension from every title
change my video category
put the same description in all of the videos
put the same keywords in all of the videos
Note: All of this would be done on the YouTube upload page. I'm using Greasemonkey in Mozilla Firefox.
I wrote this, but my question is: how do I change the HTML title in the actual HTML page to the new title (which is a Javascript variable)?
This is my code:
function remove_mp4()
{
var title = document.getElementsByName("title").value;
var new_title = title.replace(title.match(".mp4"), "");
}
function add_description()
{
var description = document.getElementsByName("description").value;
var new_description = "Subscribe."
}
function add_keywords()
{
var keywords = document.getElementsByName("keywords").value;
var new_keywords = prompt("Enter keywords.", "");
}
function change_category()
{
var category = document.getElementsByName("category").value;
var new_category = "<option value="27">Education</option>"
}
remove_mp4();
add_description();
add_keywords();
change_category();
Note: If you see any mistakes in the JavaScript code, please let me know.
Note 2: If you wonder why I stored the current HTML values in variables, that's because I think I will have to use them in order to replace HTML values (I may be wrong).
A lot of things have been covered already, but still i would like to remind you that if you are looking for cross browser compatibility innerHTML won't be enough, as you may need innerText too or textContent to tackle some old versions of IE or even using some other way to modify the content of an element.
As a side note innerHTML is considered from a great majority of people as deprecated though some others still use it. (i'm not here to debate about is it good or not to use it but this is just a little remark for you to checkabout)
Regarding remarks, i would suggest minimizing the number of functions you create by creating some more generic versions for editing or adding purposes, eg you could do the following :
/*
* #param $affectedElements the collection of elements to be changed
* #param $attribute here means the attribute to be added to each of those elements
* #param $attributeValue the value of that attribute
*/
function add($affectedElements, $attribute, $attributeValue){
for(int i=0; i<$affectedElements.length; i++){
($affectedElements[i]).setAttribute($attribute, $attributeValue);
}
}
If you use a global function to do the work for you, not only your coce is gonna be easier to maintain but also you'll avoid fetching for elements in the DOM many many times, which will considerably make your script run faster. For example, in your previous code you fetch the DOM for a set of specific elements before you can add a value to them, in other words everytime your function is executed you'll have to go through the whole DOM to retrieve your elements, while if you just fetch your elements once then store in a var and just pass them to a function that's focusing on adding or changing only, you're clearly avoiding some repetitive tasks to be done.
Concerning the last function i think code is still incomplete, but i would suggest you use the built in methods for manipulating HTMLOption stuff, if i remember well, using plain JavaScript you'll find yourself typing this :
var category = document.getElem.... . options[put-index-here];
//JavaScript also lets you create <option> elements with the Option() constructor
Anyway, my point is that you would better use JavaScript's available methods to do the work instead of relying on innerHTML fpr anything you may need, i know innerHTML is the simplest and fastest way to get your work done, but if i can say it's like if you built a whole HTML page using and tags only instead of using various semantic tags that would help make everything clearer.
As a last point for future use, if you're interested by jQuery, this will give you a different way to manipulate your DOM through CSS selectors in a much more advanced way than plain JavaScript can do.
you can check out this link too :
replacement for innerHTML
I assume that your question is only about the title changing, and not about the rest; also, I assume you mean changing all elements in the document that have "title" as name attribute, and not the document title.
In that case, you could indeed use document.getElementsByName("title").
To handle the name="title" elements, you could do:
titleElems=document.getElementsByName("title");
for(i=0;i<titleElems.length;i++){
titleInner=titleElems[i].innerHTML;
titleElems[i].innerHTML=titleInner.replace(titleInner.match(".mp4"), "");
}
For the name="description" element, use this: (assuming there's only one name="description" element on the page, or you want the first one)
document.getElementsByName("description")[0].value="Subscribe.";
I wasn't really sure about the keywords (I haven't got a YouTube page in front of me right now), so this assumes it's a text field/area just like the description:
document.getElementsByName("keywords")[0].value=prompt("Please enter keywords:","");
Again, based on your question which just sets the .value of the category thingy:
document.getElementsByName("description")[0].value="<option value='27'>Education</option>";
At the last one, though, note that I changed the "27" into '27': you can't put double quotes inside a double-quoted string assuming they're handled just like any other character :)
Did this help a little more? :)
Sry, but your question is not quite clear. What exactly is your HTML title that you are referring to?
If it's an element that you wish to modify, use this :
element.setAttribute('title', 'new-title-here');
If you want to modify the window title (shown in the browser tab), you can do the following :
document.title = "the new title";
You've reading elements from .value property, so you should write back it too:
document.getElementsByName("title").value = new_title
If you are refering to changing text content in an element called title try using innerHTML
var title = document.getElementsByName("title").value;
document.getElementsByName("title").innerHTML = title.replace(title.match(".mp4"), "");
source: https://developer.mozilla.org/en-US/docs/DOM/element.innerHTML
The <title> element is an invisible one, it is only displayed indirectly - in the window or tab title. This means that you want to change whatever is displayed in the window/tab title and not the HTML code itself. You can do this by changing the document.title property:
function remove_mp4()
{
document.title = document.title.replace(title.match(".mp4"), "");
}
is it possible to get the ID assigned to User Control from the control using javascript or jquery.
Thanks
What ASP.NET normally does is prefix your control's ID with a string that it uses to determine where in ASP.NET's control tree your actual control resides.
With that in mind, what I normally do is to use jQuery's 'ends with' selector to get the full ASP.NET-parsed ID at runtime.
Something like:
// get a handle on your original control
var myControl = $('[id$="<myOriginalId>"]');
// and then access it's properties
var myRuntimeId = myControl.eq(0).attr('id');
As you can most probably imagine, that's not going to cut it when you've got UserControls with the same ID used in different places of the form. I just jump in and put in some tweaks here and there (probably with using the .eq() function) to suit my business need.
You could put a class on the usercontrol, and then use something like $(".myUC").attr("id")
This might help you to look at it from a different point of view:
In .Net you can get the generated ID by using myControl.ClientID.
If you put that in a javascript variable - I know it's not neat - you can then easily fetch it.
<!--mypage.aspx-->
<script>
var myIdVar = "<%=myControl.ClientID%>";
if(myIdVar == "foo")
{
alert("bar");
}
</script>
For example in javascript code running on the page we have something like:
var data = '<html>\n <body>\n I want this text ...\n </body>\n</html>';
I'd like to use and at least know if its possible to get the text in the body of that html string without throwing the whole html string into the DOM and selecting from there.
First, it's a string:
var arbitrary = '<html><body>\nSomething<p>This</p>...</body></html>';
Now jQuery turns it into an unattached DOM fragment, applying its internal .clean() method to strip away things like the extra <html>, <body>, etc.
var $frag = $( arbitrary );
You can manipulate this with jQuery functions, even if it's still a fragment:
alert( $frag.filter('p').get() ); // says "<p>This</p>"
Or of course just get the text content as in your question:
alert( $frag.text() ); // includes "This" in my contrived example
// along with line breaks and other text, etc
You can also later attach the fragment to the DOM:
$('div#something_real').append( $frag );
Where possible, it's often a good strategy to do complicated manipulation on fragments while they're unattached, and then slip them into the "real" page when you're done.
The correct answer to this question, in this exact phrasing, is NO.
If you write something like var a = $("<div>test</div>"), jQuery will add that div to the DOM, and then construct a jQuery object around it.
If you want to do without bothering the DOM, you will have to parse it yourself. Regular expressions are your friend.
It would be easiest, I think, to put that into the DOM and get it from there, then remove it from the DOM again.
Jquery itself is full of tricks like this. It's adding all sorts off stuff into the DOM all the time, including when you build something using $('<p>some html</p>'). So if you went down that road you'd still effectively be placing stuff into the DOM then removing it again, temporarily, except that it'd be Jquery doing it.
John Resig (jQuery author) created a pure JS HTML parser that you might find useful. An example from that page:
var dom = HTMLtoDOM("<p>Data: <input disabled>");
dom.getElementsByTagName("body").length == 1
dom.getElementsByTagName("p").length == 1
Buuuut... This question contains a constraint that I think you need to be more critical of. Rather than working around a hard-coded HTML string in a JS variable, can you not reconsider why it's that way in the first place? WHAT is that hard-coded string used for?
If it's just sitting there in the script, re-write it as a proper object.
If it's the response from an AJAX call, there is a perfectly good jQuery AJAX API already there. (Added: although jQuery just returns it as a string without any ability to parse it, so I guess you're back to square one there.)
Before throwing it in the DOM that is just a plain string.
You can sure use REGEX.
I want to edit some HTML I get from a var I saved. like:
var testhtml = $('.agenda-rename').html();
console.log($('input',testhtml).attr('name'));
Also tried
console.log($(testhtml).find('input').attr('name'));
But i get undefined? I figured it'd work like an $.ajax, $.get, $.post? How else can i do it?
When you call .html(), you're only getting the content, not the .agenda-rename. So if the input is a direct child of .agenda-rename, then .find() won't be able to find it.
Probably better just to do without the .html() call:
var testhtml = $('.agenda-rename').clone(); // or .clone(true)
console.log($('input',testhtml).attr('name'));
Now you have the .agenda-rename element(s) and you'll be able to search for elements nested inside it/them.
EDIT: Based on comment, OP doesn't want to modify the original. As such, .clone() can be used. Answer above has been edited to reflect change.
If events are attached that should be retained, then you use .clone(true).
EDIT: The reason $('input',testhtml) and $(testhtml).find('input') give the same result is that they are actually the same thing.
jQuery converts the first version into the second behind the scenes. As such it is technically a little more efficient to use the second than the first.
Here's the code where jQuery makes the switch (after running a bunch of other tests to determine what it was passed).
http://github.com/jquery/jquery/blob/master/src/core.js#L150