jQuery Manipulation methods: Get/Set methods (text(), attr(), html(), val())

ચાર methods, એક overload rule: કોઈ argument નથી તો reads, argument હોય તો writes. plain text માટે text(), markup માટે html(), form fields માટે val(), attributes માટે attr().

11 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

seat counter ને live રહેવું પડે

Garba Night નું card બતાવે છે Seats left: 350. registration આવે છે; page હવે કહેવું જોઈએ 349 reload વગર.

એટલે તમારા script ને read કરવાની જરૂર છે કે element હાલમાં શું hold કરે છે, compute, અને તેને write back કરવું. same register link ના destination માટે, અને search box ના typed value માટે.

jQuery બધું cover કરે છે 4 methods સાથે જે એક elegant trick ને share કરે છે: દરેક reader AND writer બંને છે, તમે તેને કેવી રીતે call કરો છો તેના પર depend.

Formula

overload rule

કોઈ argument નથી = GET. Argument = SET.

$("#seats").text() text ને reads કરે છે.

$("#seats").text("349") તેને writes કરે છે.

એક name, 2 jobs, brackets ના contents દ્વારા decided. આ lesson ની બધી 4 methods તેને follow કરે છે, અને જ્યારે SET multi-element selection પર runs થાય છે, તે દરેક matched element પર લખે છે એક સાથે.

At a glance

4 get/set methods

MethodWorks onGet returnsSet does
text()Element content, plainબધા matches નું COMBINED textcontent ને Replaces કરે છે; tags literally show થાય છે
html()Element content, markupFirst match નું inner HTMLcontent ને Replaces કરે છે; tags RENDER થાય છે
val()Form fields (input, select)First field નું current valuefield ને Fills કરે છે
attr("name")Attributes (href, src, id...)First match નું attributeattr("name", v) તેને બધા પર sets કરે છે

Practical

counter ticks down (complete page)

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    $(document).ready(function() {
      $("#bookBtn").click(function() {
        var seats = parseInt($("#seats").text());   // GET, પછી convert
        if (seats > 0) {
          $("#seats").text(seats - 1);              // SET plain text
        }
        if (seats - 1 === 0) {
          $("#status").html("<b>House Full!</b>");  // SET rendered markup
          $("#regLink").attr("href", "waitlist.html"); // SET attribute
        }
        alert("Booked for: " + $("#name").val());   // GET form value
      });
    });
  </script>
</head>
<body>
  <p>Seats left: <span id="seats">350</span></p>
  <p id="status">Open</p>
  <input id="name" placeholder="Your name">
  <button id="bookBtn">Book</button>
  <a id="regLink" href="register.html">Register</a>
</body>
</html>

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Theory

text vs html: distinction જેની teeth છે

બંને content ને write કરે છે; difference એ છે કે string માં tags સાથે શું થાય છે:

$("#status").html("<b>Full!</b>") Full! ને bold માં render કરે છે: browser markup ને parse કરે છે.

$("#status").text("<b>Full!</b>") 7 characters <b>Full!</b> ને literally display કરે છે: tags visible text બને છે.

કયું use કરવું? તમારા OWN markup માટે, html(). કંઈ પણ જે USER typed (names, comments), હંમેશા text(): તેને markup અથવા scripts ને તમારા page માં inject કરવા માટે trick નથી કરી શકાતું. તે safety habit નું security name છે જે તમે પછી meet કરશો; હવે build કરો.

એક more read: $("#seats").text() String return કરે છે; arithmetic ને parseInt ની જરૂર છે first, જેમ listing કરે છે.

Quiz

$("#status").text("<b>House Full!</b>") visitor #status ની અંદર શું જુએ છે?

  1. bold letters માં House Full!
  2. literal characters <b>House Full!</b>, tags screen પર visible
  3. normal weight માં House Full!: tags silently remove થાય છે
  4. Nothing: text() strings ને reject કરે છે જેમાં tags હોય
Show the answer

literal characters <b>House Full!</b>, tags screen પર visible

text() તેના argument ને PLAIN TEXT તરીકે treats કરે છે: દરેક character as-is lands થાય છે, તેથી angle brackets અને b letters display થાય છે, interpret નથી થતા. bold render કરવું (option A) એ html() નું job છે: આ pair exam નો favourite one-word-apart comparison છે. Option C sanitising filter ને invent કરે છે જે કોઈ method પાસે નથી: text tags ને show કરે છે, html તેને obeys કરે છે, કોઈ તેને delete નથી કરતું. Option D validation ને imagine કરે છે જે exist નથી કરતું. choosing rule: તમારું own markup html() દ્વારા, કંઈ પણ user-typed text() દ્વારા, હંમેશા.

Think first

get જે differently behave કરે છે

ત્રણ event cards match $(".eventName"). compare કરો શું $(".eventName").html() અને $(".eventName").text() return કરે છે. 4 methods માંથી એક odd one out છે multi-element GETS પર: કયું, અને કેવી રીતે?

Show the answer

text() odd one છે: તે બધા MATCHED elements નું COMBINED text return કરે છે, concatenated ("Garba NightCoding ContestRobo Race"). html(), val() અને attr() first match only માંથી return કરે છે. Sets uniform છે (બધી 4 દરેક match પર લખે છે); gets એ જ્યાં text() ranks ને breaks કરે છે. Practical consequence: set માંથી ONE card નું name વાંચવા માટે, selection ને પહેલાં narrow કરો ($(".eventName:first").text()) rather than get પર trust કરવું કે તે તમારા માટે pick કરશે.

Watch out

ત્રણ manipulation bugs

get પર Arithmetic: text() અને val() Strings return કરે છે; "350" - 1 luck થી works કરે છે પણ "350" + 1 એ "3501" છે. parseInt first, દરેક time (BCA404 નો InputBox lesson અહીં rhymes કરે છે).

user input સાથે html(): visitor જે markup ને તમારા page માં type કરે છે html() set દ્વારા એ real attack surface છે; user content માટે text() non-negotiable છે.

fields પર val() vs text(): input નું typed content એ તેનું VALUE છે; $("#name").text() તેના (empty) element content ને reads કરે છે અને કંઈ useful return નથી કરતું.

Theory

Read-modify-write એ આખો pattern છે

seat counter એ template છે dynamic UI work ના અડધા માટે: GET current state, plain JavaScript માં compute, SET new state: 3 lines, કોઈ પણ widget. તેને verbatim reuse કરશો જ્યારે AJAX responses Unit 4 માં arrive થશે (server data આ same setters દ્વારા lands થશે: responseText ને html() માં poured). next lesson page ને itself grows કરે છે: append, prepend, before અને after: existing ones ને edit કરવાને બદલે brand-new elements ને adding.

Summary

Key takeaways

  • એક overload rule: કોઈ argument gets, argument sets (sets બધા matches પર apply થાય છે).
  • text() = plain text (sets tags ને literally show કરે છે; multi-get બધા matches નું COMBINED text return કરે છે).
  • html() = markup (sets tags ને render કરે છે; get first match ને reads કરે છે).
  • val() = form-field values; attr("name") / attr("name", v) = attributes.
  • Gets Strings return કરે છે: arithmetic પહેલાં parseInt.
  • User-typed content ને text() સાથે set કરો, ક્યારેય html() નહીં: કોઈ markup injection નહીં.
  • Memory hook: empty brackets ask, full brackets tell.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from jQuery Fundamentals

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

jQuery Manipulation methods: Get/Set methods (text(), attr(), html(), val()) · Web Designing-2 (option A) · Gri-Learn