Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Tuesday, December 6, 2016

JavaScript DOM Manipulation - jQuery - CSS - Q&A

Question:

Write code that shows how to give a class to all X tag elements in an HTML page using CSS | JS | JQUERY

Answer

// CSS

div{

    background: rgba(0, 180, 0, .3);

    width: 150px;

    height: 150px; }


// JavaScript

var divs = document.getElementsByTagName('DIV');

for (i in divs){

    divs[i].className = "newDivClass";

};


// jQuery

var divs = $('DIV');

$.each(divs, function(index){

    divs[index].className = "newDivClass"

});


JavaScript - jQuery - DOM Manipulation - Q&A

Question:

Output all elements count and print them to the page in the following format :








Answer

var all = $('*');
console.log( all.length );
var elements = [];
for (var i = 0;  i < all.length;  i++){
    if (!elements[$(all[i]).prop('tagName')])
        elements[$(all[i]).prop('tagName')] = 1;
    else
        elements[$(all[i]).prop('tagName')]++;
};
console.log(elements);

JavaScript - jQuery templates - Q&A

Question:

Build a jQuery template to show the following JSON in HTML table (“al” stands for a table row):
 
var data {"al":[

    {"id":"0","a":[{"txt":"Person","id":0},

    {"txt":"Description","id":0}]},

    {"id":"1","a":[{"txt":"Maxi","id":1},

        {"txt":"a rock star","id":2}]},

    {"id":"2","a":[{"txt":"Rocky","id":3},

        {"txt":"a rock star's friend","id":4}]},

    {"id":"3","a":[{"txt":"Linda Chavez","id":5},

        {"txt":"a reporter","id":6}]},

    {"id":"4","a":[{"txt":"Bill Winter","id":7},

        {"txt":"an announcer on a radio show","id":8}]}]};
 

Answer


<script id="dataTemplate" type="text/x-jquery-tmpl">
<table>
<tr>
 <th>id</th>
 <th>txt</th>
 <th>id</th>
 <th>txt</th>
</tr>
{{each al}}
 <tr>
{{each a}}
    <td>
    ${id}
    </td>
    <td>
    ${txt}
    </td>
  {{/each}}
 <tr>
{{/each}}
</table>
</script>

JavaScript - jQuery - 'this' keyword - Scope - Q&A

Question:

What is the difference between this and $(this) when used in the following bound function?

Answer

Using $(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.


JavaScript - jQuery selectors - Q&A

Question:

Give examples for the following jQuery selectors:
1) Select all paragraphs with the class “yellow”
2) Select all <div> tags by name “green”

Answer